/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.gk.handler;

import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.gk.common.RuntimeEnv;
import cn.ac.iie.di.wx.gk.httpService.HttpSender;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class CmdRevokeHandler implements HandlerI {

    Logger logger = Logger.getLogger(CmdRevokeHandler.class.getName());

    @Override
    public void init() throws Exception {
    }

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String commitCmd = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
        logger.info("revoke cmd is " + commitCmd);
        logger.info("revoke url is " + (String) RuntimeEnv.getParam(RuntimeEnv.revoke));
        //获取指令响应，根据提交的指令请求，向tx获取指令响应
        HttpSender hs = new HttpSender();
        String responseCmd = hs.closableHttpClient(commitCmd, (String) RuntimeEnv.getParam(RuntimeEnv.revoke));//json的字符串
//        String responseCmd = "{\"statuscode\":0,\"statusinfo\":\"ok\"}";
        logger.info("revoke response cmd is " + responseCmd);
        InputStream inputStream = new ByteArrayInputStream(responseCmd.getBytes("UTF-8"));
        if (responseCmd.equals("")) {
            //连接超时
            inputStream = new ByteArrayInputStream("{\"statuscode\":-1,\"statusinfo\":\"not ok\"}".getBytes("UTF-8"));
        }
        //返回指令结果
        ServletOutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        byte[] bytesContent = new byte[1024 * 2];
        int bytesReadIn = 0;
        while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
            bos.write(bytesContent, 0, bytesReadIn);
        }
        bos.flush();
        bos.close();
    }

}
